﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Diagnostics.Contracts;
using Microsoft.Practices.ServiceLocation;
using YasharEl.Infrastructure.ObjectFactory.Unity.Configuration;

namespace YasharEl.Infrastructure.ObjectFactory.Unity
{
    public static class UnityExtensions
    {
        static UnityServiceLocator unityServiceLocator;
        internal static bool Initialized { get; set; }

        internal static IUnityContainer InitializeServiceLocator(this IUnityContainer container, string containerName = null)
        {
            Contract.Requires<ArgumentNullException>(container != null, "container could not be null.");
            if (!Initialized)
            {
                unityServiceLocator = new UnityServiceLocator(container);
                ServiceLocator.SetLocatorProvider(() => unityServiceLocator);
                Initialized = true;
                DependencyContainer.Initialized = true;
            }

            if (!string.IsNullOrEmpty(containerName))
            {
                container.RegisterInstance<IUnityContainer>(
                    containerName,
                    container,
                    new ContainerControlledLifetimeManager());
                container.RegisterInstance<IDependencyRegistrar>(
                    containerName,
                    new UnityDependencyRegistrar(container),
                    new ContainerControlledLifetimeManager());
            }
            else
            {
                container.RegisterInstance<IUnityContainer>(
                    container,
                    new ContainerControlledLifetimeManager());
                container.RegisterInstance<IDependencyRegistrar>(
                    new UnityDependencyRegistrar(container),
                    new ContainerControlledLifetimeManager());
            }

            return container;
        }

        public static IUnityContainer ConfigureUnityContainer(this IUnityContainer container, System.Configuration.Configuration config)
        {
            Contract.Requires<ArgumentNullException>(container != null, "container could not be null.");
            UnityLoader loader = new UnityLoader();
            loader.Load(container, config);

            return container;
        }
    }
}
